package npu.dce.andcontact1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

class Group_Join_Server3 implements Runnable{
    
	private String SERVERIP = "10.0.2.15";
    private int SERVERPORT = 7000;

    private int count;
    private InetAddress inetadd;
    private DatagramSocket socket;
    private byte[] buf;
    private DatagramPacket receive_packet;    
    private ContactDBAdapter mDbHelper_server;
	
    public Group_Join_Server3(ContactDBAdapter mDbHelper) {
    	mDbHelper_server = mDbHelper;
    }
 
    @Override
    public void run() {
    	// TODO Auto-generated method stub        
        	try {
        		
        		inetadd = InetAddress.getByName(SERVERIP);
        		socket = new DatagramSocket(SERVERPORT, inetadd);
        		count = 0;
        		
        		while(true){          			        		    			
        			try{        				
        				buf = new byte[1920];
        				receive_packet = new DatagramPacket(buf,buf.length);

        				socket.setSoTimeout(6000); // 6 sec 
        				
        				Thread t = new Thread(new Group_Join_Client_Off2(mDbHelper_server)); 
        				Thread t1 = new Thread(new Group_Join_Client_Off3(mDbHelper_server)); 
        				
        				try{        					
        					socket.receive(receive_packet);        					        					   				 
            				break;            				            				
        				} catch(SocketTimeoutException  e){           					
        			        t.start();         			        
        			        count++;        			        
        			        if(count == 3){ 
        			        	t1.start();        			        	
        			        	break;
        			        }
        				} 
 			    		        
        			} catch(IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch(NullPointerException e) {
                    	// TODO Auto-generated catch block
                    	e.printStackTrace();	
                    }                  
        		} //while          		
        } catch (UnknownHostException e) {
        	// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();       
        }         
    } //run    
} //Group_Join_Server3